#include "mainwindow.h"
#include "codeeditor.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QComboBox>
#include <QPushButton>
#include <QTextEdit>
#include <QLineEdit>
#include <QSplitter>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QApplication>
#include <QDesktopServices>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , codeEditor(new CodeEditor(this))
    , outputConsole(new QTextEdit(this))
    , compileProcess(new QProcess(this))
    , runProcess(new QProcess(this))
    , debugProcess(nullptr)
    , inputLineEdit(new QLineEdit(this))
    , currentFile("")
    , isDebugging(false)
{
    setupUI();
    setupMenuBar();
    setupToolBar();
    setupStatusBar();
    setupConnections();

    // 设置窗口属性
    setWindowTitle("CJJ_IDE");
    resize(1000, 700);
    showMaximized(); // 启动时最大化

    codeEditor->setPlainText(
        ""
        );
}

MainWindow::~MainWindow()
{
}

void MainWindow::setupUI()
{
    // 创建中央部件和布局
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // 创建分割器
    QSplitter *splitter = new QSplitter(Qt::Vertical, centralWidget);

    // 设置代码编辑器
    codeEditor->setFont(QFont("Consolas", 11));

    // 设置输出控制台
    outputConsole->setFont(QFont("Consolas", 10));
    outputConsole->setReadOnly(true);

    // 创建一个包含输出控制台和输入行的小部件
    QWidget *consoleWidget = new QWidget;
    QVBoxLayout *consoleLayout = new QVBoxLayout(consoleWidget);
    consoleLayout->setContentsMargins(0, 0, 0, 0);
    consoleLayout->setSpacing(2); // 在控制台和输入行之间添加一点间距

    inputLineEdit->setFont(QFont("Consolas", 10));
    inputLineEdit->setPlaceholderText("在此处为您的程序输入内容，然后按 Enter 键...");
    inputLineEdit->setEnabled(false); // 初始状态为禁用

    consoleLayout->addWidget(outputConsole);
    consoleLayout->addWidget(inputLineEdit);


    // 添加部件到分割器
    splitter->addWidget(codeEditor);
    splitter->addWidget(consoleWidget);

    // 设置分割比例
    splitter->setStretchFactor(0, 4);
    splitter->setStretchFactor(1, 1);

    mainLayout->addWidget(splitter);
    setCentralWidget(centralWidget);
}

void MainWindow::setupMenuBar()
{
    // 文件菜单
    QMenu *fileMenu = menuBar()->addMenu("文件");

    QAction *newAction = fileMenu->addAction("新建");
    newAction->setShortcut(QKeySequence::New);

    QAction *openAction = fileMenu->addAction("打开");
    openAction->setShortcut(QKeySequence::Open);

    QAction *saveAction = fileMenu->addAction("保存");
    saveAction->setShortcut(QKeySequence::Save);

    QAction *saveAsAction = fileMenu->addAction("另存为");
    saveAsAction->setShortcut(QKeySequence::SaveAs);

    fileMenu->addSeparator();

    QAction *exitAction = fileMenu->addAction("退出");
    exitAction->setShortcut(QKeySequence::Quit);

    // 构建菜单
    QMenu *buildMenu = menuBar()->addMenu("构建");

    QAction *compileAction = buildMenu->addAction("编译");
    compileAction->setShortcut(QKeySequence("Ctrl+B"));

    QMenu *runMenu = menuBar()->addMenu("运行");
    QAction *runPythonAction = runMenu->addAction("运行Python");
    runPythonAction->setShortcut(QKeySequence("Ctrl+Y"));
    connect(runPythonAction, &QAction::triggered, this, [this]() {
        this->runPython();
    });

    QAction *runAction = buildMenu->addAction("运行");
    runAction->setShortcut(QKeySequence("Ctrl+R"));

    QAction *compileRunAction = buildMenu->addAction("编译并运行");
    compileRunAction->setShortcut(QKeySequence("F5"));

    QAction *clearOutputAction = buildMenu->addAction("清除输出");

    //调试菜单
    QMenu *debugMenu = menuBar()->addMenu("调试");
    debugAction = debugMenu->addAction("开始调试");
    stepIntoAction = debugMenu->addAction("单步进入");
    stepOverAction = debugMenu->addAction("单步执行");
    stepOutAction = debugMenu->addAction("单步跳出");
    continueAction = debugMenu->addAction("继续执行");
    pauseAction = debugMenu->addAction("暂停执行");
    clearBreakpointsAction = debugMenu->addAction("清除所有断点");

    // 视图菜单
    QMenu *viewMenu = menuBar()->addMenu("视图");
    QAction *zoomInAction = viewMenu->addAction("放大");
    zoomInAction->setShortcut(QKeySequence::ZoomIn);
    QAction *zoomOutAction = viewMenu->addAction("缩小");
    zoomOutAction->setShortcut(QKeySequence::ZoomOut);
    QAction *resetZoomAction = viewMenu->addAction("重置字体大小");
    resetZoomAction->setShortcut(QKeySequence("Ctrl+0"));

    // 帮助菜单
    QMenu *helpMenu = menuBar()->addMenu("帮助");

    QAction *aboutAction = helpMenu->addAction("关于");

    // 连接信号槽 - 使用 Lambda 表达式解决重载问题
    connect(newAction, &QAction::triggered, this, [this]() {
        this->newFile();
    });

    connect(openAction, &QAction::triggered, this, [this]() {
        this->openFile();
    });

    connect(saveAction, &QAction::triggered, this, [this]() {
        this->saveFile();
    });

    connect(saveAsAction, &QAction::triggered, this, [this]() {
        this->saveAsFile();
    });

    connect(exitAction, &QAction::triggered, this, &QWidget::close);

    connect(compileAction, &QAction::triggered, this, [this]() {
        this->compileCode();
    });

    connect(runAction, &QAction::triggered, this, [this]() {
        this->runCode();
    });

    connect(compileRunAction, &QAction::triggered, this, [this]() {
        this->compileAndRun();
    });

    connect(clearOutputAction, &QAction::triggered, this, [this]() {
        this->clearOutput();
    });

    connect(aboutAction, &QAction::triggered, this, [this]() {
        this->about();
    });

    connect(zoomInAction, &QAction::triggered, this, &MainWindow::zoomIn);
    connect(zoomOutAction, &QAction::triggered, this, &MainWindow::zoomOut);
    connect(resetZoomAction, &QAction::triggered, this, &MainWindow::resetZoom);
    connect(debugAction, &QAction::triggered, this, &MainWindow::debugCode);
    connect(stepIntoAction, &QAction::triggered, this, &MainWindow::stepInto);
    connect(stepOverAction, &QAction::triggered, this, &MainWindow::stepOver);
    connect(stepOutAction, &QAction::triggered, this, &MainWindow::stepOut);
    connect(continueAction, &QAction::triggered, this, &MainWindow::continueExecution);
    connect(pauseAction, &QAction::triggered, this, &MainWindow::pauseExecution);
    connect(clearBreakpointsAction, &QAction::triggered, this, &MainWindow::clearBreakpoints);
}

void MainWindow::setupToolBar()
{
    QToolBar *toolBar = addToolBar("主工具栏");

    // 使用 Lambda 表达式连接工具栏动作
    toolBar->addAction("新建", this, [this]() { this->newFile(); });
    toolBar->addAction("打开", this, [this]() { this->openFile(); });
    toolBar->addAction("保存", this, [this]() { this->saveFile(); });

    toolBar->addSeparator();

    toolBar->addAction("编译", this, [this]() { this->compileCode(); });
    toolBar->addAction("运行", this, [this]() { this->runCode(); });
    toolBar->addAction("编译并运行", this, [this]() { this->compileAndRun(); });
    toolBar->addAction("运行Python", this, [this]() {
        this->runPython();
    });
    // 调试工具按钮
    toolBar->addSeparator();
    toolBar->addAction("开始调试", this, &MainWindow::debugCode);
    toolBar->addAction("单步进入", this, &MainWindow::stepInto);
    toolBar->addAction("单步执行", this, &MainWindow::stepOver);
    toolBar->addAction("单步跳出", this, &MainWindow::stepOut);
    toolBar->addAction("继续执行", this, &MainWindow::continueExecution);
    toolBar->addAction("暂停执行", this, &MainWindow::pauseExecution);

    toolBar->addSeparator();

    toolBar->addAction("放大", this, &MainWindow::zoomIn);
    toolBar->addAction("缩小", this, &MainWindow::zoomOut);

    toolBar->addSeparator();

    // 编译器选择
    toolBar->addWidget(new QLabel("编译器:"));
    compilerComboBox = new QComboBox();
    compilerComboBox->addItems({"g++", "clang++", "gcc", "clang", "javac"});
    compilerComboBox->setCurrentText("g++");
    toolBar->addWidget(compilerComboBox);
}



void MainWindow::setupStatusBar()
{
    statusLabel = new QLabel("就绪");
    statusBar()->addWidget(statusLabel);

    // 添加行列信息标签
    QLabel *positionLabel = new QLabel("行: 1, 列: 1");
    statusBar()->addPermanentWidget(positionLabel);

    // 连接代码编辑器的光标位置变化信号
    connect(codeEditor, &CodeEditor::cursorPositionChanged, this, [positionLabel, this]() {
        QTextCursor cursor = codeEditor->textCursor();
        int line = cursor.blockNumber() + 1;
        int column = cursor.columnNumber() + 1;
        positionLabel->setText(QString("行: %1, 列: %2").arg(line).arg(column));
    });
}

void MainWindow::setupConnections()
{
    connect(compileProcess, &QProcess::readyReadStandardOutput,
            this, &MainWindow::processOutput);
    connect(compileProcess, &QProcess::readyReadStandardError,
            this, &MainWindow::processError);
    connect(compileProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &MainWindow::processFinished);

    connect(runProcess, &QProcess::readyReadStandardOutput,
            this, &MainWindow::processOutput);
    connect(runProcess, &QProcess::readyReadStandardError,
            this, &MainWindow::processError);
    connect(runProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &MainWindow::processFinished);

    connect(inputLineEdit, &QLineEdit::returnPressed, this, &MainWindow::onInputEntered);
    connect(codeEditor, &CodeEditor::zoomInRequested, this, &MainWindow::zoomIn);
    connect(codeEditor, &CodeEditor::zoomOutRequested, this, &MainWindow::zoomOut);
    connect(codeEditor, &CodeEditor::lineNumberAreaClicked, this, &MainWindow::toggleBreakpoint);
    connect(codeEditor, &CodeEditor::breakpointsChanged, this, &MainWindow::setBreakpoints);
}

void MainWindow::newFile()
{
    if (maybeSave()) {
        codeEditor->clear();
        currentFile.clear();
        setWindowTitle("CJJ_IDE - 未命名");
        statusLabel->setText("已创建新文件");
    }
}

void MainWindow::openFile()
{
    if (maybeSave()) {
        QString fileName = QFileDialog::getOpenFileName(this, "打开文件",
                                                        "", "代码文件 (*.cpp *.h *.hpp *.c *.java *.py);;C++ 文件 (*.cpp *.h *.hpp *.c);;Java 文件 (*.java);;Python 文件 (*.py)");
        if (!fileName.isEmpty()) {
            loadFile(fileName);
        }
    }
}

bool MainWindow::saveFile()  // 返回类型改为 bool
{
    if (currentFile.isEmpty()) {
        return saveAsFile();  // 现在可以返回 saveAsFile() 的结果
    } else {
        return saveFile(currentFile);  // 返回保存操作的结果
    }
}

bool MainWindow::saveAsFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存文件",
                                                    "", "C++ 文件 (*.cpp);;Java 文件 (*.java);;Python 文件 (*.py)");
    if (!fileName.isEmpty()) {
        return saveFile(fileName);
    }
    return false;
}

void MainWindow::debugCode()
{
    if (currentFile.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先保存文件。");
        return;
    }

    // 清除所有断点
    breakpoints.clear();
    updateBreakpointsDisplay();

    outputConsole->clear();
    outputConsole->append("==> 开始调试...");
    outputConsole->append("注意：调试器可能需要一些时间启动，请耐心等待。");

    statusLabel->setText("调试中...");
    isDebugging = true;

    // 禁用编译和运行按钮
    compileAction->setEnabled(false);
    runAction->setEnabled(false);
    compileRunAction->setEnabled(false);

    // 创建调试进程
    debugProcess = new QProcess(this);
    connect(debugProcess, &QProcess::readyReadStandardOutput,
            this, &MainWindow::processOutput);
    connect(debugProcess, &QProcess::readyReadStandardError,
            this, &MainWindow::processError);
    connect(debugProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &MainWindow::debugFinished);

    // 根据文件类型启动不同的调试器
    if (currentFile.endsWith(".cpp") || currentFile.endsWith(".c")) {
        // C++ 使用 gdb
        QString executable = QFileInfo(currentFile).baseName();
#ifdef Q_OS_WIN
        executable += ".exe";
#endif
        QString executablePath = QFileInfo(currentFile).absolutePath() + QDir::separator() + executable;

        if (!QFile::exists(executablePath)) {
            QMessageBox::warning(this, "警告", "未找到可执行文件。请先编译。");
            isDebugging = false;
            debugProcess->deleteLater();
            debugProcess = nullptr;
            compileAction->setEnabled(true);
            runAction->setEnabled(true);
            compileRunAction->setEnabled(true);
            return;
        }

        // 启动 gdb
        debugProcess->start("gdb", QStringList() << "-q" << executablePath);
        // 等待 gdb 提示符
        QTimer::singleShot(1000, this, [this]() {
            if (isDebugging) {
                // 设置断点
                for (auto &bp : breakpoints) {
                    debugProcess->write(QString("break %1:%2\n").arg(bp.first).arg(bp.second).toLocal8Bit());
                }
                // 运行程序
                debugProcess->write("run\n");
            }
        });
    }
    else if (currentFile.endsWith(".java")) {
        // Java 使用 jdb
        QString className = QFileInfo(currentFile).baseName();
        QString classFilePath = QFileInfo(currentFile).absolutePath() + QDir::separator() + className + ".class";

        if (!QFile::exists(classFilePath)) {
            QMessageBox::warning(this, "警告", "未找到 .class 文件。请先编译。");
            isDebugging = false;
            debugProcess->deleteLater();
            debugProcess = nullptr;
            compileAction->setEnabled(true);
            runAction->setEnabled(true);
            compileRunAction->setEnabled(true);
            return;
        }

        // 启动 jdb
        debugProcess->start("jdb", QStringList() << "-classpath" << QFileInfo(currentFile).absolutePath() << className);
        // 等待 jdb 提示符
        QTimer::singleShot(1000, this, [this, className]() {  // 添加 className 到捕获列表
            if (isDebugging) {
                // 设置断点
                for (auto &bp : breakpoints) {
                    debugProcess->write(QString("stop at %1:%2\n").arg(className).arg(bp.first).toLocal8Bit());
                }
                // 运行程序
                debugProcess->write("run\n");
            }
        });
    }
    else if (currentFile.endsWith(".py")) {
        // Python 使用 pdb
        // 启动 pdb
        debugProcess->start("python", QStringList() << "-m" << "pdb" << currentFile);
        // 等待 pdb 提示符
        QTimer::singleShot(1000, this, [this]() {
            if (isDebugging) {
                // 设置断点
                for (auto &bp : breakpoints) {
                    debugProcess->write(QString("break %1:%2\n").arg(bp.first).arg(bp.second).toLocal8Bit());
                }
                // 运行程序
                debugProcess->write("continue\n");
            }
        });
    }
    else {
        QMessageBox::warning(this, "警告", "不支持的文件类型进行调试。");
        isDebugging = false;
        debugProcess->deleteLater();
        debugProcess = nullptr;
        compileAction->setEnabled(true);
        runAction->setEnabled(true);
        compileRunAction->setEnabled(true);
        return;
    }
}

void MainWindow::stepInto()
{
    if (isDebugging && debugProcess) {
        debugProcess->write("step\n");
    }
}

void MainWindow::stepOver()
{
    if (isDebugging && debugProcess) {
        debugProcess->write("next\n");
    }
}

void MainWindow::stepOut()
{
    if (isDebugging && debugProcess) {
        debugProcess->write("finish\n");
    }
}

void MainWindow::continueExecution()
{
    if (isDebugging && debugProcess) {
        debugProcess->write("continue\n");
    }
}

void MainWindow::pauseExecution()
{
    if (isDebugging && debugProcess) {
        // 在 gdb 中，暂停使用 'kill' 命令
        debugProcess->write("kill\n");
        isDebugging = false;
    }
}

void MainWindow::clearBreakpoints()
{
    breakpoints.clear();
    codeEditor->setBreakpoints(QList<int>()); // 清空编辑器中的断点显示
    updateBreakpointsDisplay();
}



void MainWindow::addBreakpoint(int line)
{
    // 检查是否已存在断点
    for (auto &bp : breakpoints) {
        if (bp.first == line) {
            return;
        }
    }

    breakpoints.append(QPair<int, int>(line, 0));
    updateBreakpointsDisplay();

    if (isDebugging && debugProcess) {
        if (currentFile.endsWith(".cpp") || currentFile.endsWith(".c")) {
            debugProcess->write(QString("break %1\n").arg(line).toLocal8Bit());
        }
        else if (currentFile.endsWith(".java")) {
            debugProcess->write(QString("stop at %1:%2\n").arg(QFileInfo(currentFile).baseName()).arg(line).toLocal8Bit());
        }
        else if (currentFile.endsWith(".py")) {
            debugProcess->write(QString("break %1\n").arg(line).toLocal8Bit());
        }
    }
}

void MainWindow::removeBreakpoint(int line)
{
    for (int i = 0; i < breakpoints.size(); i++) {
        if (breakpoints[i].first == line) {
            breakpoints.removeAt(i);
            break;
        }
    }
    updateBreakpointsDisplay();

    if (isDebugging && debugProcess) {
        debugProcess->write(QString("clear %1\n").arg(line).toLocal8Bit());
    }
}

void MainWindow::toggleBreakpoint(int line)
{
    if (breakpoints.contains(QPair<int, int>(line, 0))) {
        removeBreakpoint(line);
    } else {
        addBreakpoint(line);
    }
}

void MainWindow::updateBreakpointsDisplay()
{
    // 在状态栏显示断点信息
    statusLabel->setText(QString("调试中, 断点: %1").arg(breakpoints.size()));

    // 将断点转换为 QList<int> 并传递给编辑器
    QList<int> bpLines;
    for (const auto &bp : breakpoints) {
        bpLines.append(bp.first);
    }
    codeEditor->setBreakpoints(bpLines);
}

void MainWindow::setBreakpoints(const QList<int> &bp)
{
    // 将 QList<int> 转换为 QList<QPair<int, int>>
    breakpoints.clear();
    for (int line : bp) {
        breakpoints.append(QPair<int, int>(line, 0));
    }
    updateBreakpointsDisplay();
}

void MainWindow::debugFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    isDebugging = false;
    statusLabel->setText("调试结束");
    outputConsole->append(QString("==> 调试结束, 退出代码: %1").arg(exitCode));

    // 启用编译和运行按钮
    compileAction->setEnabled(true);
    runAction->setEnabled(true);
    compileRunAction->setEnabled(true);

    // 清理调试进程
    debugProcess->deleteLater();
    debugProcess = nullptr;
}

void MainWindow::compileCode()
{
    if (!saveFile()) {
        QMessageBox::warning(this, "警告", "请先保存文件才能编译。");
        return;
    }

    QString compiler = compilerComboBox->currentText();
    QString sourceFile = currentFile;
    QStringList arguments;

    outputConsole->clear();
    outputConsole->append("==> 正在编译...");

    statusLabel->setText("正在编译...");
    compileProcess->setWorkingDirectory(QFileInfo(sourceFile).absolutePath());

    // Python不需要编译
    if (sourceFile.endsWith(".py")) {
        outputConsole->append("==> Python文件不需要编译。");
        return;
    }

    if (compiler == "javac") {
        // Java compilation
        arguments << sourceFile;
        compileProcess->start("javac", arguments);
    } else {
        // C++ compilation
        QString executable = QFileInfo(sourceFile).baseName();
#ifdef Q_OS_WIN
        executable += ".exe";
#endif
        arguments << sourceFile << "-o" << executable << "-std=c++17";
        compileProcess->start(compiler, arguments);
    }
}

void MainWindow::runCode()
{
    if (currentFile.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先保存文件。");
        return;
    }

    runProcess->setWorkingDirectory(QFileInfo(currentFile).absolutePath());
    inputLineEdit->setEnabled(true);
    inputLineEdit->setFocus();
    statusLabel->setText("正在运行...");

    if (currentFile.endsWith(".py")) {
        // Run Python code
        outputConsole->append("\n==> 正在运行Python程序...");
        outputConsole->append("----------------------------------------\n");
        runProcess->start("python", QStringList() << currentFile);
    } else if (currentFile.endsWith(".java")) {
        // Java compilation
        QString className = QFileInfo(currentFile).baseName();
        QString classFilePath = QFileInfo(currentFile).absolutePath() + QDir::separator() + className + ".class";

        if (!QFile::exists(classFilePath)) {
            QMessageBox::warning(this, "警告", "未找到 .class 文件。请先编译。");
            inputLineEdit->setEnabled(false);
            statusLabel->setText("就绪");
            return;
        }
        outputConsole->append("\n==> 正在运行程序...");
        outputConsole->append("----------------------------------------\n");
        runProcess->start("java", QStringList() << className);
    } else {
        // C++ compilation
        QString executable = QFileInfo(currentFile).baseName();
#ifdef Q_OS_WIN
        executable += ".exe";
#endif

        QString executablePath = QFileInfo(currentFile).absolutePath() + QDir::separator() + executable;

        if (!QFile::exists(executablePath)) {
            QMessageBox::warning(this, "警告", "未找到可执行文件。请先编译。");
            inputLineEdit->setEnabled(false);
            statusLabel->setText("就绪");
            return;
        }
        outputConsole->append("\n==> 正在运行程序...");
        outputConsole->append("----------------------------------------\n");
        runProcess->start(executablePath);
    }
}

void MainWindow::runPython()
{
    if (currentFile.isEmpty() || !currentFile.endsWith(".py")) {
        QMessageBox::warning(this, "警告", "请先保存Python文件。");
        return;
    }

    runProcess->setWorkingDirectory(QFileInfo(currentFile).absolutePath());
    inputLineEdit->setEnabled(true);
    inputLineEdit->setFocus();
    statusLabel->setText("正在运行Python程序...");

    outputConsole->append("\n==> 正在运行Python程序...");
    outputConsole->append("----------------------------------------\n");
    runProcess->start("python", QStringList() << currentFile);
}

void MainWindow::compileAndRun()
{
    if (currentFile.isEmpty()) {
        if (!saveAsFile()) {
            QMessageBox::warning(this, "警告", "请先保存文件。");
            return;
        }
    }

    // 先编译，然后在编译完成后运行
    // 创建一个一次性连接
    QMetaObject::Connection connection = connect(compileProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
                                                 [this](int exitCode, QProcess::ExitStatus exitStatus) {
                                                     // 断开这个一次性连接
                                                     QObject::disconnect(compileProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), nullptr, nullptr);
                                                     if (exitCode == 0) {
                                                         // 编译成功，运行程序
                                                         runCode();
                                                     }
                                                 });

    compileCode();
}

void MainWindow::clearOutput()
{
    outputConsole->clear();
    statusLabel->setText("输出已清除");
}

void MainWindow::updateStatusBar()
{
    // 可以添加更多状态栏更新逻辑
}

void MainWindow::processOutput()
{
    QProcess *process = qobject_cast<QProcess*>(sender());
    if (process) {
        QByteArray output = process->readAllStandardOutput();
        outputConsole->moveCursor(QTextCursor::End);
        outputConsole->insertPlainText(QString::fromLocal8Bit(output));
        outputConsole->moveCursor(QTextCursor::End);
    }
}

void MainWindow::processError()
{
    QProcess *process = qobject_cast<QProcess*>(sender());
    if (process) {
        QByteArray error = process->readAllStandardError();
        outputConsole->moveCursor(QTextCursor::End);
        outputConsole->insertHtml("<font color='red'>" + QString::fromLocal8Bit(error).toHtmlEscaped() + "</font>");
        outputConsole->moveCursor(QTextCursor::End);
    }
}

void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    QProcess *process = qobject_cast<QProcess*>(sender());
    if (process == compileProcess) {
        if (exitCode == 0) {
            outputConsole->append("==> 编译成功!");
            statusLabel->setText("编译成功");
        } else {
            outputConsole->append("<font color='red'>==> 编译失败!</font>");
            statusLabel->setText("编译失败");
        }
    } else if (process == runProcess) {
        outputConsole->append("----------------------------------------");
        if (exitStatus == QProcess::NormalExit) {
            outputConsole->append(QString("==> 程序执行完成，退出代码: %1").arg(exitCode));
        } else {
            outputConsole->append(QString("<font color='red'>==> 程序异常终止。</font>"));
        }
        statusLabel->setText("程序执行完成");
        inputLineEdit->setEnabled(false);
    }
}

void MainWindow::onInputEntered()
{
    if (runProcess->state() == QProcess::Running) {
        QString input = inputLineEdit->text() + "\n";
        // 将用户的输入回显到控制台
        outputConsole->moveCursor(QTextCursor::End);
        outputConsole->insertPlainText(input);
        outputConsole->moveCursor(QTextCursor::End);

        // 写入进程的标准输入
        runProcess->write(input.toLocal8Bit());
        inputLineEdit->clear();
    }
}

void MainWindow::about()
{
    QMessageBox::about(this, "CJJ_IDE",
                       "<h3>CJJ_IDE</h3>"
                       "<p>版本 v3.0.0</p>"
                       "<p>开发者： 陈俊杰</p>"
                       "<p>功能:</p>"
                       "<ul>"
                       "<li>C++/Java 代码编译</li>"
                       "<li>程序运行 (支持运行时输入)</li>"
                       "<li>输出显示</li>"
                       "<li>基本代码编辑与语法高亮</li>"
                       "</ul>");
}

bool MainWindow::maybeSave()
{
    if (codeEditor->document()->isModified()) {
        QMessageBox::StandardButton ret;
        ret = QMessageBox::warning(this, "简单代码 IDE",
                                   "文档已被修改。\n"
                                   "是否保存更改?",
                                   QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if (ret == QMessageBox::Save) {
            return saveFile();  // 现在 saveFile() 返回 bool，可以正常返回
        } else if (ret == QMessageBox::Cancel) {
            return false;
        }
    }
    return true;
}

void MainWindow::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, "警告",
                             "无法打开文件: " + file.errorString());
        return;
    }

    QTextStream in(&file);
    codeEditor->setPlainText(in.readAll());
    currentFile = fileName;
    setWindowTitle("简单代码 IDE - " + QFileInfo(fileName).fileName());
    statusLabel->setText("文件已加载: " + fileName);
    codeEditor->document()->setModified(false);
}

bool MainWindow::saveFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "警告",
                             "无法保存文件: " + file.errorString());
        return false;
    }

    QTextStream out(&file);
    out << codeEditor->toPlainText();
    currentFile = fileName;
    setWindowTitle("简单代码 IDE - " + QFileInfo(fileName).fileName());
    statusLabel->setText("文件已保存: " + fileName);

    codeEditor->document()->setModified(false);
    return true;
}

void MainWindow::zoomIn()
{
    QFont editorFont = codeEditor->font();
    editorFont.setPointSize(editorFont.pointSize() + 1);
    codeEditor->setFont(editorFont);

    QFont consoleFont = outputConsole->font();
    consoleFont.setPointSize(consoleFont.pointSize() + 1);
    outputConsole->setFont(consoleFont);
    inputLineEdit->setFont(consoleFont);
}

void MainWindow::zoomOut()
{
    QFont editorFont = codeEditor->font();
    if (editorFont.pointSize() > 6) { // Minimum editor font size
        editorFont.setPointSize(editorFont.pointSize() - 1);
        codeEditor->setFont(editorFont);
    }

    QFont consoleFont = outputConsole->font();
    if (consoleFont.pointSize() > 5) { // Minimum console font size
        consoleFont.setPointSize(consoleFont.pointSize() - 1);
        outputConsole->setFont(consoleFont);
        inputLineEdit->setFont(consoleFont);
    }
}

void MainWindow::resetZoom()
{
    codeEditor->setFont(QFont("Consolas", 11));
    outputConsole->setFont(QFont("Consolas", 10));
    inputLineEdit->setFont(QFont("Consolas", 10));
}
